package com.earl.spider.util;

import org.jsoup.Jsoup;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateUtil {

    private static final String timeUrl = "http://47.112.12.109:8443/user-service/custom/time";
    private static String netPattern = "yyyy-MM-dd HH:mm:ss";

    /**
     * 格式化某时间
     *
     * @param format
     * @param date
     * @return
     */
    public static String formatDate(String format, Date date) {
        // 设置日期格式
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }


    /**
     * 将字符串时间转换为Date
     *
     * @param date
     * @param pattern
     * @return
     */
    public static Date parse(String date, String pattern) {
        return parse(date, pattern, null);
    }

    /**
     * 将字符串时间转换为Date
     *
     * @param date
     * @param pattern
     * @param locale
     * @return
     */
    public static Date parse(String date, String pattern, Locale locale) {
        SimpleDateFormat sdf;
        if (locale != null) {
            sdf = new SimpleDateFormat(pattern, locale);
        } else {
            sdf = new SimpleDateFormat(pattern);
        }
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getNetTime() {
        String result;
        try {
            // 设置北京时区
            result = Jsoup.connect(timeUrl).execute().body();
        } catch (IOException e) {
            e.printStackTrace();
            result = formatDate(netPattern, new Date());
        }
        return result;
    }

}
